package jlts.front.core;

import jlts.entity.Request;
import jlts.entity.Response;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @ClassName Client
 * @Description TODO
 * @Author Zxeao
 * @Date 2021/12/23 下午4:41
 * @Version V1.0
 */
public class Client {
    private Socket socket;

    public Client() {
        boolean loop=false;
        do{
            try {
                socket=new Socket("localhost",8080);
                //一旦连接成功就false
                loop=false;
            } catch (UnknownHostException e) {
                loop=Alert.confim("服务器地址或端口错误，请联系开发人员协调后重试");
            } catch (IOException e) {
                loop=Alert.confim("服务器未开，请联系开发人员协调后重试");
            }
        }while(loop);
    }

    /**通用方法，给我一个请求，我给你一个响应*/
    public Response send(Request request){
        try {
            OutputStream os=socket.getOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(os);
            oos.writeObject(request);

            InputStream is= socket.getInputStream();
            ObjectInputStream ois=new ObjectInputStream(is);
            Response res=(Response)ois.readObject();

            return res;
        } catch (Exception e) {
            Alert.show("数据传输错误,致命，程序即将退出");
            System.exit(0);
            e.printStackTrace();
            return new Response();
        }
    }
}
